'''
Created on 22.10.2012

@author: fixje
'''
import json, logging
from collections import deque
from knowtemarks.DataModel import Knowte

log = logging.getLogger("main.import")

class MozillaJSONImporter(object):
    def __init__(self, inFile=None):
        self.file = inFile
        self.data = None
    def setData(self, d):
        self.data = d
    def parse(self):
        if self.data is None:
            strB = json.load(self.file, encoding="utf-8")
        else:
            strB = json.loads(self.data, encoding="utf-8")
        return self._parse(strB)
    def _parse(self, jso):
        results = []
        wq = deque([jso])
        while len(wq) > 0:
            currentNode = wq.popleft()
            # add sub nodes
            if currentNode.has_key("children"):
                currentChildren = currentNode["children"]
                for i in range(0,len(currentChildren)):
                    wq.append(currentChildren[i])
                
            if not "text/x-moz-place" == currentNode["type"]:
                continue
            if not currentNode.has_key("uri") or not currentNode.has_key("title"):
                # exception
                continue
            bm = Knowte()
            bm.url = unicode(currentNode["uri"])
            bm.title = unicode(currentNode["title"])
            
            if currentNode.has_key("annos"):
                annos = currentNode["annos"]
                for i in range(0,len(annos)):
                    cAnno = annos[i]
                    if not cAnno.has_key("name") or not cAnno.has_key("value"):
                        # exception
                        continue
                    if "bookmarkProperties/description" == cAnno["name"]:
                        bm.info = unicode(cAnno["value"])
            results.append(bm)
        return results                
    

class STATE():
        init, url_begin, url, tags_begin, \
        tags, title_begin, title, desc_begin = range(8)

class DeliciousHTMLImporter(object):
    
    def __init__(self, inFile=None):
        self.file = inFile
        self.data = None
    
    def setData(self, d):
        self.data = d
        
    def parse(self):
        results = []
        if self.data == None:
            with open(self.file, "r") as f:
                strB = str(f.read())
                results = self.parseData(strB)
        else:
            results = self.parseData(self.data)
        return results
        
    def parseData(self, strB):
        results = []
        i = -1
        index = 0
        state = STATE.init
        bm = None
        while i < len(strB) - 1:
            i += 1
            if state == STATE.init:
                if i + 12 > len(strB): continue
                c = strB[i:i + 12]
                if c.lower() == "<dt><a href=":
                    bm = Knowte()
                    index = i + 13
                    i += 12
                    state = STATE.url_begin
            elif state == STATE.url_begin:
                ci = strB[i]
                if ci == '"' or ci == "'":
                    bm.url = unicode(strB[index:i])
                    state = STATE.url
            elif state == STATE.url:
                if i + 4 > len(strB): continue
                c = strB[i:i + 4]
                if c.lower() == "tags":
                    index = i + 6
                    i += 5
                    state = STATE.tags_begin
            elif state == STATE.tags_begin:
                ci = strB[i]
                if ci == "'" or ci == '"':
                    c = strB[index:i]
                    for t in c.split(","):
                        if t.count(":") < 1:
                            bm.addTag(unicode(t))
                    state = STATE.tags
            elif state == STATE.tags:
                ci = strB[i]
                if ci == ">":
                    i += 1
                    index = i
                    state = STATE.title_begin
            elif state == STATE.title_begin:
                if i + 4 > len(strB): continue
                c = strB[i:i + 4]
                if c.lower() == "</a>":
                    bm.title = unicode(strB[index:i])
                    state = STATE.title
                    i += 4
                elif c.lower() == "<dt>":
                    state = STATE.init
                    results.append(bm)
                    i -= 1
            elif state == STATE.title:
                if i + 4 > len(strB): continue
                c = strB[i:i + 4]
                if c.lower() == "<dd>":
                    index = i + 4
                    i += 3
                    state = STATE.desc_begin
                elif c.lower() == "<dt>" or c.lower() == "</dl":
                    i -= 1
                    results.append(bm)
                    state = STATE.init
            elif state == STATE.desc_begin:
                if i + 4 > len(strB): continue
                c = strB[i:i + 4]
                if c.lower() == "</dd" or c.lower() == "<dt>":
                    bm.info = unicode(strB[index:i])
                    results.append(bm)
                    state = STATE.init
                    i -= 1
        
        for n in results:
            if n.title == "":
                n.title = n.url
        return results
